package com.application.Network;

/*
 * Copyright (C) 2010 University of Parma - Italy
 * 
 * This source code is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This source code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this source code; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 * Designer(s):
 * Marco Picone (picone@ce.unipr.it)
 * Fabrizio Caramia (fabrizio.caramia@studenti.unipr.it)
 * Michele Amoretti (michele.amoretti@unipr.it)
 * 
 * Developer(s)
 * Fabrizio Caramia (fabrizio.caramia@studenti.unipr.it)
 * 
 */

import it.unipr.ce.dsg.s2p.message.Payload;
import it.unipr.ce.dsg.s2p.org.json.JSONException;
import it.unipr.ce.dsg.s2p.org.json.JSONObject;
import it.unipr.ce.dsg.s2p.peer.NeighborPeerDescriptor;
import it.unipr.ce.dsg.s2p.peer.Peer;
import it.unipr.ce.dsg.s2p.peer.PeerDescriptor;
import it.unipr.ce.dsg.s2p.sip.Address;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import org.zoolu.sip.provider.SipProvider;

import ReadWriteXML.CMember;
import ReadWriteXML.CQuestion;
import ReadWriteXML.CUsingQuestionList;
import android.app.AlertDialog;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.application.Activity.FrmTabActivity;
import com.application.Activity.MESApplication;
import com.application.Activity.frmMatKetNoiActivity;
import com.application.Activity.frmNhomChoActivity;
import com.application.Activity.frmNotificationMoiVaoNhom;


import com.application.Activity.frmTreeNodeActivity;
import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;
import com.application.DTO.AccountDTO;
import com.application.DTO.RoleDTO;
import com.application.Message.JoinMessage;
import com.application.Message.PingMessage;

import com.application.Tree.BoardView;
import com.application.Tree.INode;
import com.application.Tree.TextNode;
import com.application.Tree.TreeNode;

/**
 * Class <code>SimplePeer</code> implements many features of a peer.
 * SimplePeer extend the Peer class of sip2peer.
 * 
 * 
 * @author Fabrizio Caramia
 *
 */

public class NetworkLayer extends Peer {

	//===truc
	public AccountDTO account = null;
	private Handler hander = new Handler();
	public static int amountMemberGroup=0; 
	//==end truc
	private boolean login_error=false;
	private Address bootstrapPeer = null;
	public Boolean blgv = false;
	final private String SEPARATOR = "/";
	private String ipUser = peerDescriptor.getAddress();
	//======TRUC==============
	public PeerDescriptor getPeerDescriptor() {
		return this.peerDescriptor;
	}
	public AccountDTO getAccount() {
		return this.account;
	}
	

	public String getSimpleIP(){
		return getAddress().getHost().toString();
	}
	private boolean nhomDaFull() {
		return true;
	}
		
	//======END TRUC===============
	
	/*----------Các hàm Đăng nhập, tìm kiếm user trong mạng, Đăng xuất------------*/
	/**
	 * Hàm gửi thông tin đăng nhập đến cho giáo viên
	 * @param address: địa chỉ giáo viên gồm ip:port
	 * @param user : user name
	 * @param pass : passwork
	 */
	public void SendAccountLearnerToTeacher(Address address,String user,String pass)
	{
		Log.d("PEERDROID",peerDescriptor.getAddress().toString());
		PingMessage newPingMsg = new PingMessage(peerDescriptor);
		Payload pay=new Payload();
		pay.addParam("dn", user + SEPARATOR + pass);
		newPingMsg.setPayload(pay);
		newPingMsg.setType("DangNhap");
		Log.d("PEERDROID","Da vào hàm GuiIdChoGiaoVien");
		Log.d("PEERDROID","IP host:" + address.toString());
		//send(new Address(address), newPingMsg);
		send(address, newPingMsg);
		Log.d("PEERDROID","Da send Id cho Giao Vien");
	}

	/**
	 * Hàm gửi thông tin Log out cho giáo viên
	 * @param addr
	 */
	public void SendMessageLogout(Address addr)
	{
		Log.d("PEERDROID","Da vào hàm Gửi Thông tin Logout");
		PingMessage mesage = new PingMessage(peerDescriptor);
		Payload p = new Payload();
		p.addParam("Logout",NetworkController.get_ipUser());
		mesage.setPayload(p);
		mesage.setType("logout");
		send(addr, mesage);
		Log.d("PEERDROID","Da gửi Logout");
	}

	public void SendHelloToUser(Address addr)
	{
		Log.d("PEERDROID","Da vào hàm send hello");
		PingMessage mesage = new PingMessage(peerDescriptor);
		Payload p = new Payload();
		p.addParam("fullname", NetworkController.get_fullName());
		p.addParam("username", NetworkController.get_userName());
		mesage.setPayload(p);
		mesage.setType("hello");
		send(addr, mesage);
	}

	public void SendReHelloToUser(Address addr)
	{
		Log.d("PEERDROID","Da vào hàm send rehello : " + addr.toString());
		PingMessage mesage = new PingMessage(peerDescriptor);
		Payload p = new Payload();
		p.addParam("fullname", NetworkController.get_fullName());
		p.addParam("username", NetworkController.get_userName());
		mesage.setPayload(p);
		mesage.setType("rehello");
		send(addr, mesage);
		Log.d("PEERDROID","Da gui rehello");
	}
	/*-------------------Các nhận, gửi bài tập; thông tin feedback----------------*/

	/*----------Các hàm chat invite------------*/
	public void SendInvite(Address addr, String title)
	{
		Log.d("PEERDROID","Da vào hàm send invite");
		PingMessage mesage = new PingMessage(peerDescriptor);
		Payload p = new Payload();
		p.addParam("fullname", NetworkController.get_fullName());
		p.addParam("username", NetworkController.get_userName());
		p.addParam("info", title);
		mesage.setPayload(p);
		mesage.setType("invite");
		send(addr, mesage);
		Log.d("PEERDROID","Da gui invite");
	}	

	public void SendSignoutInvite(Address addr, String keychat)
	{
		Log.d("PEERDROID","Da vào hàm send invite_logout");
		PingMessage mesage = new PingMessage(peerDescriptor);
		Payload p = new Payload();
		p.addParam("fullname", NetworkController.get_fullName());
		p.addParam("username", NetworkController.get_userName());
		p.addParam("keychat", keychat);
		mesage.setPayload(p);
		mesage.setType("signout_invite");
		send(addr, mesage);
		Log.d("PEERDROID","Da gui invitelogout");
	}

	public void SendSignoutGroup(Address addr, String keychat)
	{
		Log.d("PEERDROID","Da vào hàm send invite_logout");
		PingMessage mesage = new PingMessage(peerDescriptor);
		Payload p = new Payload();
		p.addParam("fullname", NetworkController.get_fullName());
		p.addParam("username", NetworkController.get_userName());
		p.addParam("keychat", keychat);
		mesage.setPayload(p);
		mesage.setType("signout_group");
		send(addr, mesage);
		Log.d("PEERDROID","Da gui invitelogout");
	}

	public void SendReInvite(Address addr, int accept, String username,
			String fullname, String keyChat) {
		Log.d("PEERDROID", "Da vào hàm send reinvite");
		PingMessage mesage = new PingMessage(peerDescriptor);
		Payload p = new Payload();
		//key chat laf user name nguoi tao
		p.addParam("keychat", keyChat);
		p.addParam("accept", accept);
		p.addParam("username", username);
		p.addParam("fullname", fullname);
		mesage.setPayload(p);
		mesage.setType("reinvite");
		send(addr, mesage);
		Log.d("PEERDROID", "Da gui reinvite");
	}

	public void SendInviteGroup(Address addr, String str)
	{
		Log.d("PEERDROID","Da vào hàm send reinvite");
		PingMessage mesage = new PingMessage(peerDescriptor);
		Payload p = new Payload();
		p.addParam("grouplist", str);
		p.addParam("keychat", NetworkController.get_userName());
		mesage.setPayload(p);
		mesage.setType("invite_group");
		send(addr, mesage);
		Log.d("PEERDROID","Da gui invite_group");
	}

	public void SendInviteUpdateGroup(Address addr, CMember cmem)
	{
		Log.d("PEERDROID","Da vào hàm send inviteUpdateGroup");
		PingMessage mesage = new PingMessage(peerDescriptor);
		Payload p = new Payload();
		p.addParam("fullname", cmem.get_fullName());
		p.addParam("username", cmem.get_userName());
		p.addParam("ip", cmem.get_ip());
		p.addParam("keychat", NetworkController.get_userName());
		mesage.setPayload(p);
		mesage.setType("invite_update_group");
		send(addr, mesage);
		Log.d("PEERDROID","Da gui invite_update_group");
	}
	
	public void sendFile(Address addr, Payload p)
	{
		PingMessage mesage = new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("sendfile");
		send(addr, mesage);
	}
	/*-----------------------------Các hàm gửi thông tin bài tập, feedback cho giáo viên-------------------------------------*/
	public void SendResultToTeacher(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("feedback");
		send(new Address(addr), mesage);
	}

	public void SendFeedbackToTeacher(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("reactivefeedback");
		send(new Address(addr), mesage);
	}

	public void SendAllFeedbackToTeacher(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("reactivefeedbackall");
		send(new Address(addr), mesage);
	}

	/*-----------------------------Các hàm gửi thông tin chat-------------------------------------*/
	/*-------------Các hàm nhận, gửi thông tin chat, invite group, ...------------*/
	public void SendChatPeerMessage(Address address,String message)
	{//mess hom username/fullname/text
		PingMessage newPingMsg = new PingMessage(peerDescriptor);
		Payload pay=new Payload();
		pay.addParam("Message", message);
		newPingMsg.setPayload(pay);
		newPingMsg.setType("messageprivate");
		send(address, newPingMsg);
		Log.d("PEERDROID","gui thong diep chat peer");
	}

	/**
	 * hàm gởi một message
	 * 
	 * @param address
	 * @param message
	 */
	public void SendChatMessage(Address address, String message, String username, String type)// username cua  nguoi tap group
	{
		PingMessage newPingMsg = new PingMessage(peerDescriptor);
		Payload pay = new Payload();
		pay.addParam("Message", message);
		pay.addParam("keychat", username);
		pay.addParam("type", type);
		newPingMsg.setPayload(pay);
		newPingMsg.setType("message");
		send(address, newPingMsg);
	}

	public void SendMessageRequestExercises(Address addr) {
		Log.d("PEERDROID", "Đã vào hàm yêu cầu bài tập");
		PingMessage mesage = new PingMessage(peerDescriptor);
		Payload p = new Payload();
		p.addParam("fullname", NetworkController.get_fullName());
		mesage.setPayload(p);
		mesage.setType("requestexercises");
		send(addr, mesage);
		Log.d("PEERDROID", "Da gui yeu cau bai tap");
	}

	public void SendMessageFullTest(Address addr, CUsingQuestionList listtest, String idexercises) {
		Log.d("PEERDROID", "Da vào hàm Gửi bài tập hiện đang thực hiện");
		PingMessage mesage = new PingMessage(peerDescriptor);
		Payload p = new Payload();
		 p.addParam("time",String.valueOf(NetworkController.get_timedotest()));
		p.addParam("iddetaillearning", listtest.get_idDetailLearning());
		p.addParam("title", listtest.get_title());
		 p.addParam("idexercises",idexercises);
		p.addParam("idpart", listtest.get_idPart());
		for (int i = 0; i < listtest.get_questionList().size(); i++) {
			// idquestion/idtypequestion/content/iddetail/namedetail...##
			//lay 1 cau hoi trong danh sach
			CQuestion cques = listtest.get_questionList().get(i);
			
			//xay dung du lieu 1 cau hoi đe gui di
			String textsend = String.valueOf(cques.get_idQuestion()) + "/"
					+ String.valueOf(cques.get_type()) + "/"
					+ cques.get_content();
			int n = cques.get_length();
			for (int j = 0; j < n; j++) {
				textsend += "/" + cques.get_listOption().get(j).get_idDetail()
						+ "/" + cques.get_listOption().get(j).get_content();
			}
			//them 1 thông tin goi di
			p.addParam(String.valueOf(i + 1), textsend);
		}
		mesage.setPayload(p);
		mesage.setType("full_test");
		send(addr, mesage);
	}
	/*-----------------------------Các hàm gửi thông tin yêu cầu sub, chap, part-------------------------------------*/
	/*-----------------------------Các hàm gửi thông tin subject, chap, part-------------------------------------*/
	public void SendIDSubjectToTeacher(Address address, int idSubject, int idClass)
	{
		PingMessage newPingMsg = new PingMessage(peerDescriptor);
		Payload pay=new Payload();
		pay.addParam("idsubject", idSubject);
		pay.addParam("idclass", idClass);
		newPingMsg.setPayload(pay);
		newPingMsg.setType("get_subjectid");
		send(address, newPingMsg);
		Log.d("PEERDROID","Da send Id cho Giao Vien");
	}

	public void SendIDChapterToTeacher(Address address, int idChapter, int idClass)
	{
		PingMessage newPingMsg = new PingMessage(peerDescriptor);
		Payload pay=new Payload();
		pay.addParam("idclass", idClass);
		pay.addParam("idchapter", idChapter);
		newPingMsg.setPayload(pay);
		newPingMsg.setType("get_chapterid");
		send(address, newPingMsg);
		Log.d("PEERDROID","Da send Id cho Giao Vien");
	}

	public void SendIDPartToTeacher(Address address, int idPart, int idClass)
	{
		PingMessage newPingMsg = new PingMessage(peerDescriptor);
		Payload pay=new Payload();
		pay.addParam("idpart", idPart);
		pay.addParam("idclass", idClass);
		newPingMsg.setPayload(pay);
		newPingMsg.setType("get_partid");
		send(address, newPingMsg);
		Log.d("PEERDROID","Da send Id cho Giao Vien");
	}
	/*-----------------------------Các hàm module đồng bộ------------------------------------------*/
	public void SendUpdateList(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("updatelist");
		send(new Address(addr), mesage);
	}
	public void SendIDMax(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("idmax");
		send(new Address(addr), mesage);
	}
	public void SendUpdateSubject(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("updatesubject");
		send(new Address(addr), mesage);
	}
	public void SendRequestSubject(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("requestupdatesubject");
		send(new Address(addr), mesage);
	}
	public void SendUpdateChapter(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("updatechapter");
		send(new Address(addr), mesage);
	}
	public void SendRequestChapter(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("requestupdatechapter");
		send(new Address(addr), mesage);
	}
	public void SendUpdatePart(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("updatepart");
		send(new Address(addr), mesage);
	}
	public void SendRequestPart(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("requestupdatepart");
		send(new Address(addr), mesage);
	}
	public void SendUpdateDetailLearning(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("updatedetaillearning");
		send(new Address(addr), mesage);
	}
	public void SendRequestDetailLearning(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("requestupdatedetaillearning");
		send(new Address(addr), mesage);
	}
	public void SendUpdateExercises(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("updateexercises");
		send(new Address(addr), mesage);
	}
	public void SendRequestExercises(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("requestupdateexercises");
		send(new Address(addr), mesage);
	}
	public void SendUpdateQuestion(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("updatequestion");
		send(new Address(addr), mesage);
	}
	public void SendRequestQuestion(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("requestupdatequestion");
		send(new Address(addr), mesage);
	}
	
	/*-----------------------------Các hàm hệ thống hỗ trợ học cộng tác-----------------------------*/
	public void SendListMember(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("listmember");
		send(new Address(addr), mesage);
	}
	public void sendFeedbackGroup(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("feedbackgroup");
		send(new Address(addr), mesage);
	}
	public void SendQuestionGroup(Address addr, Payload p)
	{
		PingMessage mesage=new PingMessage(peerDescriptor);
		mesage.setPayload(p);
		mesage.setType("exercisesgroup");
		send(new Address(addr), mesage);
	}
	/*-----------------------------Các hàm hệ thống nhận và gửi-------------------------------------*/
	/**
	 * Hàm nhận tự động Message gửi đến
	 */
	@Override
	protected void onReceivedJSONMsg(JSONObject peerMsg, Address sender) {
		Log.d("PEERDROID", "Da nhan mot Message !");

		JSONObject params=null;
		try {
			params=peerMsg.getJSONObject("payload").getJSONObject("params");
		} catch (JSONException e) {

			e.printStackTrace();
		}
		try {
			Log.d("PEERDROID",peerMsg.toString());
			//=======truc=====
			String type = (String) peerMsg.get("type");
			Log.d("PingThread", "type: " + type+" from: "+sender.toString());
			if (type.equals(Protocol.STOP_TALKING_ONE_MEMBER)) {
				NetworkController.NhanYeuCauNgungThaoLuan(params, sender);				
				
			}
			//cho noi
			else if(type.equals(Protocol.ACCEPT_TALKING_ONE_MEMBER)){
				NetworkController.NhanChoPhepThaoLuan();
			}//chat
			else if(type.equals(Protocol.CHAT_PEER_MESSAGE))
			{
				//truyen thong diep qua ham chat
				Log.d("Phu","da nhan thong diep chat");
				NetworkController.ReceiveMessageChatPeerROLE(params, sender);
				
				//NetworkController.NhanTinNhanTroChuyenRieng(params, sender);
			
			}//ko co quyen nhan tin nhan chat
			else if(type.equals(Protocol.CHAT_FEEDBACK_NON_RULE)){
				
				NetworkController.CloseChatPeerActivity();
				NetworkController.NhanPhanHoiKhongCoQuyenTroChuyenRieng(params, sender);
				
			}//nhan tin nhan yeu cau bieu quyet moi nguoi khac ra khoi nhom
			else if(type.equals(Protocol.KICK_MEMBER_OUT_MESSAGE)){
				NetworkController.ReceiveVoteKickMember(params, sender);
				
			}//nhan duoc phan hoi moi nguoi khac ra khoi nhom
			else if(type.equals(Protocol.KICK_MEMBER_OUT_FEEDBACK))
			{
				Log.d("Phu","vao fan hoi vote");
			//	NetworkController.ShowMessageNotice("da nhan dc tin nhan phan hoi Kick");
				NetworkController.ReceiveFeedbackKickMember(params);
			}//nhan dc ket qua cuoi dung
			else if(type.equals(Protocol.KICK_MEMBER_OUT_RESULT)){
			//	NetworkController.ShowMessageNotice("da nhan dc ket qua Kick");
				NetworkController.ReceiveResultKickMember(params);
				
			}

			// ==================Phú==========================================

			// Nhận đc gói tin mời vào nhóm
			else if (type.equals(Protocol.GROUP_INVITE)) {
				Log.d("nhan", "nhan dc: " + type);
				if (!NetworkController.KiemTraDaVaoNhom()) {
					final String contentTitle = params.getString(Protocol.GROUP_INVITE_DATA_GROUP_NAME);
					final String contentText = params.getString(Protocol.GROUP_INVITE_DATA_MSG);
					final Address nguoiGui=sender;
					hander.post(new Runnable() {
						@Override
						public void run() {
							// ActivityController.setPeerActivity(frmPhuActivity.this);
							// ActivityController.showNotification("Có người mời bạn vào nhóm!",
							// contentTitle, contentText);
							NetworkController.sender=nguoiGui;
							ActivityController.showMoiVaoNhomNotification(contentText, contentTitle);
							//MESApplication.displayNotification("Có người mời bạn vào nhóm!", contentTitle, contentText);
							Log.d("phu", "GROUP_INVITE Nhan duoc"+contentText+"_"+contentTitle);
						}
					});

				} else {

				}
			}
			// Đồng ý vào nhóm
			else if (type.equals(Protocol.GROUP_INVITE_REPLY_YES)) {
				// Kiểm tra tình trạng nhóm xem có vào đc ko - gửi msg từ chối/
				// cho phép vào nóm
				
				if (NetworkController.checkFullGroup()) {
					Log.d("phu", "Nhom da full - ko cho vao nhom");
					NetworkController.sendKhongChoVaoNhom(sender);
				} else {
					Log.d("phu", "Cho vao nhom ");
					Log.d("phu", "host: " + sender.getHost());
					NetworkController.amountMember.add(1);
					Log.i("Phu", "reply yes hien tai ="+NetworkController.amountMember.size());
					NetworkController.sendChoVaoNhom(sender);
					
					//hander.post(frmPhuActivity.raUpdateNguoiTrongNhom);
				}
			}
			// Không thể vào nhóm - hiện thông báo ko thể vào nhóm
			else if (type.equals(Protocol.GROUP_INVITE_NO)) {
				Log.d("phu", "Ko the vao nhóm ");
				//hander.post(FrmTabActivity.raKhongDuocVaoNhom);
				
				NetworkController.ShowMessageNoticeTAB(Protocol.GROUP_INVITE_FEEDBACK_NOT_ENTER);
			}
			// Có thể vào nhóm -gửi msg join_group
			else if (type.equals(Protocol.GROUP_INVITE_YES)) {
				Log.d("phu", "Có thể vào nhóm");
				// hander.post(frmPhuActivity.raDaVaoNhom);
				Log.i("Phu", "hien tai ="+NetworkController.amountMember.size());
				hander.post(frmNotificationMoiVaoNhom.raStarNhomCho);
				NetworkController.sendJoinGroup(sender, account.get_Username(), account.get_Username());
			
			}
			// nhận đc tin Vào nhóm - Cập nhật lại member list -
			//  gửi tin cập nhật cho tất cảthành viên
			// Gửi danh sách thành viên cho thằng mới vào
			else if (type.equals(Protocol.JOIN_GROUP)) {
				// Lấy thông tin của member mới vào
				String IP = sender.toString();
				String userName = params.getString(Protocol.MEMBER_USER_NAME);
				String fullName = params.getString(Protocol.MEMBER_FULL_NAME);
				final CMember member = new CMember(IP, fullName, userName);
				int current,total;
				current=NetworkController.amountMember.size();
				total=amountMemberGroup;
				final int cur=current;
				final int tot=total;
				
				frmNhomChoActivity.insertMember(member);	
				final ArrayList<CMember> memberList = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
				NetworkController.sendMemberList(new Address(member.get_ip()), memberList,total,current);
				for (int i = 0; i < memberList.size(); i++) {
					 {
						final int j = i;
						hander.post(new Runnable() {
							@Override
							public void run() {								
								NetworkController.sendUpdateMember(new Address(memberList.get(j).get_ip()), member,tot,cur);
							}
						});
					}
				}
				hander.post(frmNhomChoActivity.raRefreshListView);
			}
			//Cập nhật member (insert thêm 1 thành viên)
			else if(type.equals(Protocol.UPDATE_MEMBER_LIST)){
				final String s=params.getString(Protocol.UPDATE_MEMBER_LIST);	
				int totalMemCount=Integer.parseInt(params.getString("Total_Member"));
				int curMemCount=Integer.parseInt(params.getString("Current_Member"));
				amountMemberGroup=totalMemCount;
				NetworkController.amountMember.clear();
				for(int i=0;i<curMemCount;i++){
					NetworkController.amountMember.add(1);
				}
				hander.post(new Runnable() {					
					@Override
					public void run() {
						frmNhomChoActivity.insertMember(CMember.parse(s));						
					}
				});
				hander.post(frmNhomChoActivity.raRefreshListView);
			}
			//Ghi danh sách thành viên xuống file - Hiện màn hình chờ nhóm
			else if(type.equals(Protocol.MEMBER_LIST)){
				int totalMemCount=Integer.parseInt(params.getString("Total_Member"));
				int curMemCount=Integer.parseInt(params.getString("Current_Member"));
				final String s=params.getString(Protocol.MEMBER_LIST);	
				amountMemberGroup=totalMemCount;
				NetworkController.amountMember.clear();
				for(int i=0;i<curMemCount;i++){
					NetworkController.amountMember.add(1);
				}
				ReadWriteFileController.writeMember(ReadWriteFileController.MEMBER_PATH,CMember.parseList(s));
				hander.post(frmNhomChoActivity.raRefreshListView);
				Log.d("Phu","Da mo man hinh Cho nhom trong network");
			}
			// Set role
			else if (type.equals(Protocol.SET_ROLE)) {
				String data = "";
				Iterator<String> iter = params.keys();
				while (iter.hasNext()) {
					String key = iter.next();					
					if (key.equals("DATA")) {
						try {
							data = params.getString(key);
							Log.d("Phu", "SET_ROLE nhận được data:" + data);
							break;
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}
				final String s = data;
				hander.post(new Runnable() {

					@Override
					public void run() {
						//Tiến hành ghi xuống file và reset role cho account
						String path = ReadWriteFileController.MY_ROLE_PATH;						
						ReadWriteFileController.writeRole(path,
								RoleDTO.parseList(MESApplication.getAppContext(),s, ReadWriteFileController.RULE_BASE_PATH));
						NetworkController.resetRole();
					}
				});
			}
			//Bắt đầu học nhóm
			else if(type.equals(Protocol.START_GROUP)){
				getAccount().setInGroup(true);
				
				ActivityController.startGroup(); 
			}
			//Thêm node vào cây
			else if(type.equals(Protocol.ADD_NODE)){
				if(sender.getHost().toString().equals(this.getSimpleIP())){
					return;
				}
				String s=params.getString(Protocol.ADD_NODE);
				long pID=Long.parseLong(params.getString(Protocol.TREENODE_ID));
				TreeNode node=new TreeNode();
				node.parse(s);
				TextNode textnode = new TextNode();
				textnode.parse(s);
				frmTreeNodeActivity.idNode=pID;
				frmTreeNodeActivity.nodeAdd=node;
				frmTreeNodeActivity.textnodeAdd=textnode;
				Log.d("Phu"," NetWorkLayer-AddNode..." + frmTreeNodeActivity.isActive);
				if(frmTreeNodeActivity.isActive){
					Log.d("Phu"," NetWorkLayer-AddNode...active nen cho vao cay luon");
					hander.post(frmTreeNodeActivity.raAddnode);
					hander.post(frmTreeNodeActivity.raAddnodetext);
				}
				else{
					Log.d("Phu","NetWorkLayer-AddNode...ko active nen ghi xuong file node: " + node.getId());					
					TreeNode tree = new TreeNode();
					if(ReadWriteFileController.isFile(BoardView.treePath)){							
						tree.readXml(BoardView.treePath);
						Log.d("Phu","NetWorkLayer-AddNode...File tồn tại nên đọc từ file lên: "+tree.getSumChildren());
					}else{
						Log.d("Phu","NetWorkLayer-AddNode...Ko tồn tại file nên createRoot: "+tree.getSumChildren());
						tree=BoardView.createRoot();
					}
					INode temp = tree.getById(pID);
					if (temp != null){
						Log.d("Phu","NetWorkLayer-AddNode...add node: " + node.getId()+" vào node " + temp.getId());
						temp.add(node);
						tree.setVersion(node.getVersion());
						Log.d("Phu","NetWorkLayer-AddNode...add node: " + tree.getSumChildren());
					}
					tree.writeXML(BoardView.treePath);
				}
				
			}
			//Cập nhật text của 1 node
			else if(type.equals(Protocol.UPDATE_NODE_TEXT)){
				String s=params.getString(Protocol.NODE_UPDATE);
				TreeNode node=new TreeNode();
				node.parse(s);
				TextNode textnode = new TextNode();
				textnode.parse(s);
				frmTreeNodeActivity.nodeAdd = node;
				frmTreeNodeActivity.textnodeAdd = textnode;
				if(frmTreeNodeActivity.isActive){
					Log.d("Phu","Active nên update vào cây luôn");
					hander.post(frmTreeNodeActivity.raUpdateTextNode);
					hander.post(frmTreeNodeActivity.raUpdateNodeText);
				}else{
					Log.d("Phu","update ko active cap nhat xuong file");
					TreeNode tree=new TreeNode();
					if(ReadWriteFileController.isFile(BoardView.treePath)){						
						tree.readXml(BoardView.treePath);						
					}else{
						tree=BoardView.createRoot();
					}
					INode temp= tree.getById(node.getId());
					if(temp!=null){
						temp.copy(node);
					}
					tree.writeXML(BoardView.treePath);
				}
			}
			//Xóa node của cây
			else if(type.equals(Protocol.DELETE_NODE_TREE)){
				if (sender.getHost().equals(getSimpleIP()))
					return;
				String s = params.getString(Protocol.DELETE_NODE_TREE);
				INode node=new TreeNode();
				node.parse(s);
				INode tnode = new TextNode();
				tnode.parse(s);
				frmTreeNodeActivity.nodeAdd=(TreeNode) node;
				frmTreeNodeActivity.textnodeAdd = (TextNode)tnode;
				if (frmTreeNodeActivity.isActive) {
					Log.d("An", "active nên delete luôn");
					hander.post(frmTreeNodeActivity.raDeleteNode);
					hander.post(frmTreeNodeActivity.raDeleteNodeText);
				} else {
					Log.d("An", " ko active nên xóa ghi xuống file");
					
					TreeNode tree = new TreeNode();
					tree.readXml(BoardView.treePath);
					INode temp = tree.getById(node.getId());
					if (temp != null){
						tree.remove(temp);
						tree.setVersion(node.getVersion());
						tree.writeXML(BoardView.treePath);
						tree.WriteToDeleteFile(node.getId(), node.getVersion());
					}					
				}
			}
			//Chat thảo luận
			else if (type.equals(Protocol.CHAT_MESSAGE)) {
				String key;
				if (account.getRuleById(Protocol.R_THAO_LUAN) != null && account.getRuleById(Protocol.R_THAO_LUAN).getReceive()) {

					Log.d("Phu", "Da show noi dung chat nhan dc");

				} else {
					Log.d("Phu", "gui phan hoi ko chat net layer");
					
				}
			}
			//Ping message
			else if(type.equals(Protocol.PING_MSG)){
				NetworkController.sendPingReply(sender);				
			}
			//Reply ping message
			else if(type.equals(Protocol.PING_MSG_REPLY)){
				NetworkController.setStated(true);
			}
			//Nhận đc yêu cầu cập nhật cây- save cây, sau đó đọc và gửi
//			else if(type.equals(Protocol.UPDATE_TREE)){
//				//frmTreeNodeActivity.writeTree();
//				String data=ReadWriteFileController.readTreeText();
//				NetworkController.sendTreeText(sender, data);
//			}
			//Cập nhật lại toàn bộ cây
			else if(type.equals(Protocol.TREE_TEXT)){
				String data=params.getString(Protocol.TREE_TEXT);
				ReadWriteFileController.writeTreeText(data);
				hander.post(frmTreeNodeActivity.raResetTree);
			}
			//Nhận đc yêu cầu lấy version cây, sau đó đọc và gửi
			else if(type.equals(Protocol.GET_VERSION)){
				//long version = BoardView.treeversion();
//				Log.d("An", "GET_VERSION-treeVersion: " +version);
				long vs = ReadWriteFileController.getVersionTree();
//				Log.d("An", "GET_VERSION-treeVersion xml..: " +vs);
				NetworkController.sendTreeText(sender, vs);
			}
			//Nhận version tu những peer khac
			else if(type.equals(Protocol.TREE_VERSION)){
				long vs = Long.parseLong(params.getString("TREE_VERSION"));
//				Log.d("An", "TREE_VERSION-treeVersion: " +vs);
				Address address = sender;
				String s = vs+"#"+address;
//				Log.d("An", "TREE_VERSION-s: " +s);
				frmMatKetNoiActivity.addVersion(s);
			}
			else if(type.equals("SEND_VERSION")){
				Log.d("An", "SEND_VERSION: ");
				long vs = Long.parseLong(params.getString("VERSION"));
				TreeNode tree = new TreeNode();
				if(frmTreeNodeActivity.isActive && frmTreeNodeActivity.board!=null){
					tree=frmTreeNodeActivity.board.getTree();
				}else{
					tree.readXml(BoardView.treePath);
				}
				Log.d("An","my vs="+tree.getVersion()+"your vs="+vs);				
				String s = tree.GetStringNode(vs);
				Log.d("An", "SEND_VERSION-node tree: " + s + s.length());
				String del = tree.readDelXML(tree.pathDeleteNode());
				Log.d("An", "SEND_VERSION-delString: "+(del==null));
				NetworkController.sendResultNode(sender, s, del);
			}
			else if(type.equals("RESULT_NODE")){
				String s = params.getString("LIST");
				String dns = params.getString("DELLIST");
				Log.d("An", "RESULT_NODE-dns: " +dns);
				Log.d("An", "RESULT_NODE-s: " +s);
				frmMatKetNoiActivity.NodeString = s;
				frmMatKetNoiActivity.DelNodeString = dns;	
				
				frmMatKetNoiActivity.dongBo(s,dns);
				frmTreeNodeActivity.board.readXml(BoardView.treePath);
				frmTreeNodeActivity.board.autoArrange();
			}
			else if(type.equals("CLEAR_NODE_TREE")){				
//				NetworkController.ReceiveDungThaoLuan(params, sender);
				Log.d("An", "NetWorkLayer_CLEAR_NODE_TREE: " );
//				hander.post(new Runnable() {
//					
//					@Override
//					public void run() {
//						// TODO Auto-generated method stub
//						ActivityController.MsgDungThaoLuan();
//					}
//				});
				NetworkController.receiveClearNode();
			}
			//end phu
			//-----------------------An-----
			else if (type.equals(Protocol.GROUP_SIGN_OUT)){
				Log.d("PEERDROID", "da nhan tin nhan request sign out");
				NetworkController.ReceiveSignOut(params, sender);
			}else if (type.equals(Protocol.GROUP_DANH_GIA)){
				/*hander.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						ActivityController.ShowDanhGia();
					}
				});*/
				NetworkController.ReceiveDanhGia(params, sender);
			}
			else if (type.equals(Protocol.BIEU_QUYET_FEEDBACK)){
				Log.d("PEERDROID", "da nhan tin nhan feedback bieu quyet");
				NetworkController.ReceiveResultBieuQuyet(params, sender);
			}
			else if (type.equals(Protocol.GROUP_BIEU_QUYET)){
				Log.d("PEERDROID", "da nhan tin nhan request bieu quyet");
				NetworkController.ReceiveBieuQuyet(params, sender);
			}
			else if (type.equals(Protocol.DANH_GIA_FEEDBACK)){
				Log.d("PEERDROID", "da nhan tin nhan feedback danh gia");
				NetworkController.ReceiveResultDanhGia(params, sender);
			}
			else if (type.equals(Protocol.RESULT_DANH_GIA)){
				Log.d("PEERDROID", "da nhan tin nhan ket qua danh gia");
				NetworkController.NhanKetQuaDanhGiaCuoiCung(params, sender);
				//NetworkController.HienThiKetQuaDanhGia();
			}
			else if (type.equals(Protocol.RESULT_BIEU_QUYET)){
				Log.d("PEERDROID", "da nhan tin nhan ket qua bieu quyet");
				//NetworkController.ReceiveResultBieuQuyet(params, sender);
				NetworkController.NhanKetQuaBieuQuyet(params, sender);
			}
			else if (type.equals(Protocol.LOG_FILE)){
				Log.d("PEERDROID", "da nhan Text log");
				NetworkController.ReceiveTextLog(params, sender);
			}
//			else if(type.equals(Protocol.ADD_TEXT_NODE)){
//				String s=params.getString("TEXT_NODE");
//				long nodeID=Long.parseLong(params.getString("TEXT_NODE_ID"));
//				TextNode node=new TextNode();
//				node.parse(s);
//				Log.d("Phu","Da add node khi nhan duoc NetworkLayer ADD_NODE");
//				Log.d("Phu","pId: "+nodeID);
//				Log.d("Phu","title"+node.getTitle());
//				frmTextNodeActivity.idNode=nodeID;
//				
//				hander.post(frmTextNodeActivity.raAddnode);
//				
//			}
			
			
			//===end truc=====
			/*-----------------Các gói tin module 1----------------------------------*/
			/*-----------------Các gói tin đăng nhập, đăng xuất, tìm kiếm user trong mạng-----------------*/
			else if(peerMsg.get("type").equals("userlist"))
			{
				Log.d("PEERDROID","Type Message là userlist");
				NetworkController.ReceiveUserList(params);
			}
			else if(peerMsg.get("type").equals("hello"))
			{
				Log.d("PEERDROID","Type Message là hello");
				NetworkController.ReceiveHello(params, sender);
			}
			else if(peerMsg.get("type").equals("rehello"))
			{
				Log.d("PEERDROID","Type Message là rehello");
				NetworkController.ReceiveReHello(params, sender);
				
			}
			else if(peerMsg.get("type").equals("infoteacher"))
			{
				Log.d("PEERDROID","Type Message là infoteacher");
				NetworkController.ReceiveInfoTeacher(params, sender);
			}
			//tin nhắn nhận thông tin account, Kết quả đăng nhập
			else if(peerMsg.get("type").equals("ReDangNhap"))
			{
				Log.d("PEERDROID","Type Message là ReDangNhap");
				NetworkController.isLogin(params);
				String ipUser = peerDescriptor.getAddress();
				int size = ipUser.length();
				if(size >= 18)
				{
					String[]temp = ipUser.split("@");
					//ipUser = ipUser.substring(size - 18, size - 1);
					ipUser = temp[1];
					NetworkController.set_ipUser(ipUser);
				}

			}
			//tin nhắn nhận thông tin đăng nhập trùn account
			else if(peerMsg.get("type").equals("duplicateaccount"))
			{
				Log.d("PEERDROID","Type Message là duplicateaccount");
				ActivityController.ShowDialogDuplicateAccount();
				//FrmSubject.get_dialog().dismiss();
			}
			//tin nhắn nhận thông tin đăng xuất của giáo viên
			else if(peerMsg.get("type").equals("logoutteacher"))
			{
				Log.d("PEERDROID","Type Message là logoutteacher");
				//ActivityController.ShowDialogTeacherLogout();
				String activity=ActivityController.getPeerActivity().getLocalClassName();
				if(activity.equals("FrmTabActivity")){
					NetworkController.ShowTeacherLogout();
				}else{
					
					NetworkController.ShowDialogTeacherLogout();
				}
				
				//MESApplication.showLogoutTeacher(); 
				
				//FrmSubject.get_dialog().dismiss();
			}
			else if(peerMsg.get("type").equals("logout"))
			{
				Log.d("PEERDROID","Type Message là logout");
				
				
				NetworkController.ReceiveUserLogout(params, sender);
			}
			/*-----------------Các gói tin nhận gửi bài tập, feedback-----------------*/
			//tin nhắn nhận bài tập
			else if(peerMsg.get("type").equals("full_test"))
			{
				Log.d("PEERDROID","Type Message là full_test");
				//ActivityController.ShowActivityDoTest(params, 1);
				
				ActivityController.ShowNotification(params, 1, 1);
			}
			//tin nhắn nhận đáp án bài tập
			else if(peerMsg.get("type").equals("full_testanswer"))
			{
				Log.d("PEERDROID","Type Message là result_test");
				NetworkController.ReceiveResultTest(params);
			}
			//tin nhắn nhập kết quả bài tập
			else if(peerMsg.get("type").equals("statistics"))
			{
				Log.d("PEERDROID","Type Message là statistics");
				ActivityController.ShowNotification(params,0 , 2);
			}
			else if(peerMsg.get("type").equals("quick_test"))
			{
				Log.d("PEERDROID","Type Message là quick_test");
				ActivityController.ShowNotification(params, 2, 1);
			}

			//tin nhắn nhận thông tin feedback
			//			if(peerMsg.get("type").equals("feeltype"))
			//			{
			//				Log.d("PEERDROID","Type Message là feeltype");
			//				NetworkController.ReceiveFeelType(params);
			//			}
			//tin nhắn nhận thông tin feedback theo kịch bản
			else if(peerMsg.get("type").equals("feedbackfeeltype"))
			{
				Log.d("PEERDROID","Type Message là feedbackfeeltype");
				NetworkController.ReceiveFeedbackFeelType(params);
			}
			//tin nhắn nhận thông tin active feedback 
			else if(peerMsg.get("type").equals("activefeedback"))
			{
				Log.d("PEERDROID","Type Message là activefeedback");
				NetworkController.ReceiveActiveFeedback(params);
			}

			//tin nhắn nhận thông tin active all feedback 
			else if(peerMsg.get("type").equals("activefeedbackall"))
			{
				Log.d("PEERDROID","Type Message là activefeedback");
				NetworkController.ReceiveActiveAllFeedback(params);
			}
			
			
			/*-----------------Các gói tin nhận thông tin class, subject, chap, part, detailLearning-----------------*/
			//tin nhắn nhận thông tin dãy id các sub, chap và part mới
			else if(peerMsg.get("type").equals("learning"))
			{
				Log.d("PEERDROID","Type Message là ID");
				//ActivityController.ShowDialog();
				NetworkController.ReceiceID(params);
			}
			//tin nhắn nhận thông tin danh sách subject
			else if(peerMsg.get("type").equals("list_subject"))
			{
				Log.d("PEERDROID","Type Message là list_subject");
				NetworkController.ReceiveSubjectList(params);
				//FrmSubject.get_dialog().dismiss();
			}
			//tin nhắn nhận thông tin subject theo 1 id đã yêu cầu
			else if(peerMsg.get("type").equals("list_subjectid"))
			{
				Log.d("PEERDROID","Type Message là list_subjecdid");
				NetworkController.ReceiveSubject(params);
				//FrmSubject.get_dialog().dismiss();
			}
			//tin nhắn nhận thông tin danh sách chapter
			else if(peerMsg.get("type").equals("list_chapter"))
			{
				Log.d("PEERDROID","Type Message là list_chapter");
				NetworkController.ReceiveChapterList(params);
			}
			//tin nhắn nhận thông tin chapter theo 1 id đã yêu cầu
			else if(peerMsg.get("type").equals("list_chapterid"))
			{
				Log.d("PEERDROID","Type Message là list_chaptedid");
				NetworkController.ReceiveChapter(params);
			}
			//tin nhắn nhận thông tin danh sách part
			else if(peerMsg.get("type").equals("list_part"))
			{
				Log.d("PEERDROID","Type Message là list_part");
				NetworkController.ReceivePartList(params);
			}
			//tin nhắn nhận thông tin part theo 1 id đã yêu cầu
			else if(peerMsg.get("type").equals("list_partid"))
			{
				Log.d("PEERDROID","Type Message là list_partid");
				NetworkController.ReceivePart(params);
			}
			//tin nhắn nhận thông tin detailLearning
			else if(peerMsg.get("type").equals("list_detaillearning"))
			{
				Log.d("PEERDROID","Type Message là list_detaillearning");
				NetworkController.ReceiveDetailLearning(params);
			}


			/*----------------------Các tin nhắn module 2------------------------------*/
			//tin nhắn nhận thông tin chia nhóm từ máy giảng viên
			else if(peerMsg.get("type").equals("grouping"))
			{
				//nhan du lieu ghi xuong
				NetworkController.ReceiveGrouping(params);

			}
			//tin nhắn nhận message update lại nhóm
			else if(peerMsg.get("type").equals("updategrouping"))
			{
				//nhan du lieu ghi xuong
				ReadWriteFileController.WriteUpdateGroup(params);
				ActivityController.updateListUser();
			} 
			else if(peerMsg.get("type").equals("signout_group"))
			{
				//truyen thong diep qua ham chat
				Log.d("PEERDROID","da nhan tin nhan signout_group");				
				NetworkController.ReceiveSignoutGroup(params, sender);
			}
			//tin nhắn nhận message chat group học tập
			else if(peerMsg.get("type").equals("message"))
			{
				//truyen thong diep qua ham chat
				NetworkController.ReceiveMessageChatGroup(params);

			}
			//tin nhắn nhận message chat cá nhân
			else if(peerMsg.get("type").equals("messageprivate"))
			{
				//truyen thong diep qua ham chat
				NetworkController.ReceiveMessageChatPeer(params, sender);
				Log.d("PEERDROID","da nhan tin nhan chat peer");				
			}
			/*----------------------Các gói tin inviteGroup------------------------------*/
			else if(peerMsg.get("type").equals("invite"))
			{
				Log.d("PEERDROID","da nhan tin nhan invite");
				NetworkController.ReceiveInvite(params, sender);
			}
			else if(peerMsg.get("type").equals("reinvite"))
			{
				//truyen thong diep qua ham chat
				Log.d("PEERDROID","da nhan tin nhan reinvite");				
				NetworkController.ReceiveReInvite(params, sender);
			}
			else if(peerMsg.get("type").equals("signout_invite"))
			{
				//truyen thong diep qua ham chat
				Log.d("PEERDROID","da nhan tin nhan invite_logout");				
				NetworkController.ReceiveInviteLogout(params, sender);
			}

			//tin nhắn thông tin danh sách thành viên trong nhóm được invite
			else if(peerMsg.get("type").equals("invite_group"))
			{
				//truyen thong diep qua ham chat
				Log.d("PEERDROID","da nhan tin nhan invite_group");				
				NetworkController.ReceiveInviteGroup(params, sender);
			}
			else if(peerMsg.get("type").equals("invite_update_group"))
			{
				//truyen thong diep qua ham chat
				Log.d("PEERDROID","da nhan tin nhan invite_update_group");				
				NetworkController.ReceiveInviteUpdateGroup(params, sender);
			}
			
			else if(peerMsg.get("type").equals("sendfile"))
			{
				//truyen thong diep qua ham chat
				Log.d("PEERDROID","da nhan tin nhan sendfile");				
				NetworkController.RecevieFile(params, sender);
			}
			
			//------ các gói cho việc tương tác trao đổi dữ liệu giữa các neighbor-------------

			else if (peerMsg.get("type").equals("requestexercises")) {
				// truyen thong diep qua ham chat
				Log.d("PEERDROID", "da nhan tin nhan yeu cau bai tap");
				//gui bai tap duoc yeu cau di (là bài tap dang lam)
				CUsingQuestionList cUsingQ=NetworkController.getUsingQuestionList();
				String idexercises = NetworkController.getIdExercises();
				NetworkController.SendTestExercire(sender,cUsingQ,idexercises);
				
			}
			/*-----------------các gói tin module đồng bộ----------------------------*/
			else if(peerMsg.get("type").equals("requestupdatesubject")){
				Log.d("PEERDROID","da nhan tin nhan requestupdatesubject");				
				NetworkController.ReceiveRequestSubject(params, sender);
			}
			else if(peerMsg.get("type").equals("requestupdatechapter")){
				Log.d("PEERDROID","da nhan tin nhan requestupdatechapter");	
				NetworkController.ReceiveRequestChapter(params, sender);
			}
			else if(peerMsg.get("type").equals("requestupdatepart")){
				Log.d("PEERDROID","da nhan tin nhan requestupdatepart");	
				NetworkController.ReceiveRequestPart(params, sender);
			}
			else if(peerMsg.get("type").equals("requestupdatedetaillearning")){
				Log.d("PEERDROID","da nhan tin nhan requestupdatedetaillearning");	
				NetworkController.ReceiveRequestDetailLearning(params, sender);
			}
			else if(peerMsg.get("type").equals("requestupdateexercises")){
				Log.d("PEERDROID","da nhan tin nhan requestupdateexercises");	
				NetworkController.ReceiveRequestExercises(params, sender);
			}
			else if(peerMsg.get("type").equals("requestupdatequestion")){
				Log.d("PEERDROID","da nhan tin nhan requestupdatequestion");	
				NetworkController.ReceiveRequestQuestion(params, sender);
			}
			else if(peerMsg.get("type").equals("updatesubject")){
				Log.d("PEERDROID","da nhan tin nhan updatesubject");	
				NetworkController.ReceiveUpdateSubject(params);
			}
			else if(peerMsg.get("type").equals("updatechapter")){
				Log.d("PEERDROID","da nhan tin nhan updatechapter");	
				NetworkController.ReceiveUpdateChapter(params);
			}
			else if(peerMsg.get("type").equals("updatepart")){
				Log.d("PEERDROID","da nhan tin nhan updatepart");	
				NetworkController.ReceiveUpdatePart(params);
			}
			else if(peerMsg.get("type").equals("updatedetaillearning")){
				Log.d("PEERDROID","da nhan tin nhan updatedetaillearning");	
				NetworkController.ReceiveUpdateDetailLearning(params);
			}
			else if(peerMsg.get("type").equals("updateexercises")){
				Log.d("PEERDROID","da nhan tin nhan updateexercises");	
				NetworkController.ReceiveUpdateExercises(params);
			}
			else if(peerMsg.get("type").equals("updatequestion")){
				Log.d("PEERDROID","da nhan tin nhan updatequestion");	
				NetworkController.ReceiveUpdateQuestion(params);
			}
			else if(peerMsg.get("type").equals("idmax")){
				Log.d("PEERDROID","da nhan tin nhan idmax");	
				NetworkController.ReceiveIDMax(params);
			}
			else if(peerMsg.get("type").equals("updatelist")){
				Log.d("PEERDROID","da nhan tin nhan updatelist");	
				NetworkController.ReceiveUpdateList(params);
			}
			else if(peerMsg.get("type").equals("updatenow")){
				Log.d("PEERDROID","da nhan tin nhan updatenow");	
				NetworkController.ReceiveUpdateListNow(params);
			}
			else if(peerMsg.get("type").equals("idmax")){
				Log.d("PEERDROID","da nhan tin nhan idmax");	
				NetworkController.ReceiveIDMax(params);
			}
			/*--------------------------------------module đồng bộ--------------------------------------*/
			else if(peerMsg.get("type").equals("groupinvite")){
				Log.d("PEERDROID","da nhan tin nhan groupinvite");	
				NetworkController.ReceiveGroupInvite(params);
			}
			else if(peerMsg.get("type").equals("exercisesgroup"))
			{
				Log.d("PEERDROID","da nhan tin nhan exercisesgroup");
				NetworkController.ReceiveExercisesGroup(params);				
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	protected void onDeliveryMsgFailure(String arg0, Address arg1, String arg2) {
		// TODO Auto-generated method stub
		Log.d("PEERDROID","Send Message that bai");
		AlertDialog.Builder alert=new AlertDialog.Builder(ActivityController.getPeerActivity());
		alert.setTitle("Error Connect");
		alert.setMessage("Kết nối không được tới máy chủ !");
		alert.setPositiveButton("Đồng ý", null);
		alert.create().show();

	}

	@Override
	protected void onDeliveryMsgSuccess(String arg0, Address arg1, String arg2) {
		// TODO Auto-generated method stub
		Log.d("PEERDROID","Send Message thanh cong");
	}


	/*------------------------------Các hàm khởi tạo---------------------------*/
	public NetworkLayer(String pathConfig, String key, String peerName,
			int peerPort) {
		super(pathConfig, key, peerName, peerPort);
		peerDescriptor.setContactAddress(SipProvider.AUTO_CONFIGURATION);

	}
	


	public NetworkLayer(String pathConfig, String key, String name, int port, AccountDTO account) {
		// TODO Auto-generated constructor stub
		super(pathConfig, key, name, port);
		this.account=account;
	}
	public String getAddressPeer(){		

		return getAddress().getURL();
	}

	public String getContactAddressPeer(){

		return peerDescriptor.getContactAddress();
	}

	public ArrayList<String> getListAddressPeer(){

		ArrayList<String> addressList = new ArrayList<String>();
		Iterator<NeighborPeerDescriptor> iter = this.peerList.values().iterator();
		PeerDescriptor peerDesc = new PeerDescriptor();
		Integer sizeList = new Integer(this.peerList.size());

		while(iter.hasNext()){
			peerDesc = iter.next();	
			addressList.add(peerDesc.getContactAddress());
		}

		return addressList;
	}

	public void pingToPeer(String address){

		PingMessage newPingMsg = new PingMessage(peerDescriptor);
		Payload pay=new Payload();
		newPingMsg.setType("getSubjects");
		Log.d("PEERDROID","Da vào hàm PingtoPeer");
		send(new Address(address), newPingMsg);

	}

	public void joinToPeer(Address address){

		JoinMessage newJoinMsg = new JoinMessage(peerDescriptor);
		Payload pay=new Payload();
		Log.d("PEERDROID","Da vào hàm jointoPeer");
		newJoinMsg.setType("trac_nghiem");
		send(new Address(address), newJoinMsg);

	}


	public void setConfiguration(String sbc, String bootstrap, String reachability){

		nodeConfig.sbc=sbc;
		nodeConfig.test_address_reachability=reachability;
		setBootstrapPeer(new Address(bootstrap));

	}

	public void contactSBC(){		
		requestPublicAddress();		
	}

	public Address getBootstrapPeer() {
		return bootstrapPeer;
	}

	private void setBootstrapPeer(Address bootstrapPeer) {
		this.bootstrapPeer = bootstrapPeer;
	}

	public String getSBCAddress(){		
		return nodeConfig.sbc;
	}
	/**
	 * @param login_error the login_error to set
	 */
	public void setLogin_error(boolean login_error) {
		this.login_error = login_error;
	}

	/**
	 * @return the login_error
	 */
	public boolean isLogin_error() {
		return login_error;
	}

	public void sendInfoReDangnhap(Address addr, Payload p) {
		// TODO Auto-generated method stub
		PingMessage message = new PingMessage(peerDescriptor);
		message.setPayload(p);
		message.setType("inforedangnhap");
		send(addr,message);
	}


}
